package com.itheima.tliasbackend.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tliasbackend.utils.JwtUtils;
import com.itheima.tliasbackend.utils.Result;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * LoginCheckFilter
 *
 * @author liliudong
 * @version 1.0
 * @description
 * @date 2023/5/24 16:52
 */
@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        // HttpServletRequest
        // HttpServletResponse
        // 类型转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 2. 获取URL
        String url = request.getRequestURL().toString();

        // 3. 判断url是不是登录
        if (url.contains("/login")) {
            // 是登录，放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 不是登录
        // 4. 获取请求头的jwt
        String jwt = request.getHeader("token");

        // 5.判断jwt是否存在
        if (StringUtils.hasLength(jwt)) {
            // 没有Jwt，返回 { "code": 0, "msg": "NOT_LOGIN", "data": null }
            Result notLogin = Result.error("NOT_LOGIN");
            // 对象 --> 序列化 json
            String json = JSONObject.toJSONString(notLogin);
            // 给前端返回json
            response.getWriter().write(json);
            return;
        }

        // 6. 解析jwt是否合法
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            Result notLogin = Result.error("NOT_LOGIN");
            // 对象 --> 序列化 json
            String json = JSONObject.toJSONString(notLogin);
            // 给前端返回json
            response.getWriter().write(json);
            return;
        }

        // 合法放行 - 过滤器链
        filterChain.doFilter(servletRequest, servletResponse);

    }


}
